package yb.ecp.fast.infra.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.IndexedColors;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 导出Excel公共方法
 *
 * @version 1.0
 */
@Slf4j
public class ExportUtil {

//    private static void setHttpResponse(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
//        response.setCharacterEncoding("utf-8");
//        response.setHeader("Content-Disposition",
//                "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//        response.setContentType("application/x-msdownload");
//    }
//
//    public static void exportXlsx(HttpServletResponse response, String fileName, String sheetName, List<String> headers,
//                                  List<List<Object>> records) {
//        commonExportXlsx(response, fileName, sheetName, headers, records, null);
//    }
//
//    public static void exportXlsxWithCommonStyle(HttpServletResponse response, String fileName, String sheetName, List<String> headers,
//                                                 List<List<Object>> records) {
//        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
//        HorizontalCellStyleStrategy horizontalCellStyleStrategy = genCommonHorizontalCellStyleStrategy();
//        commonExportXlsx(response, fileName, sheetName, headers, records, horizontalCellStyleStrategy);
//    }
//
//    private static HorizontalCellStyleStrategy genCommonHorizontalCellStyleStrategy() {
//        //通用的样式(可以调整)
//        WriteCellStyle headWriteCellStyle = genCommonWriteCellStyle();
//        // 内容的策略
//        WriteCellStyle contentWriteCellStyle = genWriteCellStyle();
//        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
//        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
//                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
//        return horizontalCellStyleStrategy;
//    }

    private static WriteCellStyle genWriteCellStyle() {
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
//        contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        // 背景
//        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE1.getIndex());
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 10);
        contentWriteFont.setBold(false);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        return contentWriteCellStyle;
    }

    private static WriteCellStyle genCommonWriteCellStyle() {
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 10);
        headWriteFont.setBold(false);
        headWriteCellStyle.setWriteFont(headWriteFont);
        return headWriteCellStyle;
    }
//
//    public static void commonExportXlsx(HttpServletResponse response, String fileName, String sheetName, List<String> headers,
//                                        List<List<Object>> records, HorizontalCellStyleStrategy horizontalCellStyleStrategy) {
//        OutputStream outputStream = null;
//        try {
//            setHttpResponse(fileName, response);
//            outputStream = response.getOutputStream();
//            if (horizontalCellStyleStrategy != null) {
//                EasyExcel.write(outputStream).registerWriteHandler(horizontalCellStyleStrategy)
//                        .head(genExcelHead(headers, sheetName)).sheet(sheetName)
//                        .doWrite(records);
//            } else {
//                EasyExcel.write(outputStream)
//                        .head(genExcelHead(headers, sheetName)).sheet(sheetName)
//                        .doWrite(records);
//            }
//
//        } catch (Exception e) {
//            log.error("exportXlsx error", e);
//            throw new RuntimeException("导出数据出现异常");
//        } finally {
//            if (null != outputStream) {
//                IOUtils.closeQuietly(outputStream);
//            }
//        }
//    }


    private static List<List<String>> genExcelHead(List<String> title, String sheetName) {
        return title.stream().map(x -> {
            List<String> list = new ArrayList<>();
            list.addAll(Collections.singletonList(sheetName));
            list.add(x);
            return list;
        }).collect(Collectors.toList());
    }

//    /**
//     * 分页写
//     *
//     * @param response
//     * @param fileName
//     * @param sheetName
//     * @param headers
//     * @param records
//     * @param page
//     * @param pagedExport
//     */
//    public static void repeatedWrite(HttpServletResponse response, String fileName, String sheetName, List<String> headers,
//                                     List<List<Object>> records,
//                                     IPage page,
//                                     PagedExport pagedExport) {
//        OutputStream outputStream = null;
//        ExcelWriter excelWriter = null;
//        try {
//            setHttpResponse(fileName, response);
//            outputStream = response.getOutputStream();
//
//            //通用的样式(可以调整)
//            WriteCellStyle headWriteCellStyle = genCommonWriteCellStyle();
//            // 内容的策略
//            WriteCellStyle contentWriteCellStyle = genWriteCellStyle();
//            // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
//            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
//                    new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
//            excelWriter = EasyExcel.write(outputStream).build();
//            WriteSheet writeSheet = EasyExcel.writerSheet(sheetName)
//                    .head(genExcelHead(headers, sheetName)).registerWriteHandler(horizontalCellStyleStrategy)
//                    .build();
//
//            excelWriter.write(records, writeSheet);
//            while (true) {
//                page.setCurrent(page.getCurrent() + 1);
//                page.setRecords(null);
//                List ll = pagedExport.process(page);
//                if (CollectionUtils.isEmpty(ll)) {
//                    break;
//                }
//                excelWriter.write(ll, writeSheet);
//                if (ll.size() < page.getSize()) {
//                    break;
//                }
//            }
//        } catch (Exception e) {
//            log.error("exportXlsx error", e);
//            throw new RuntimeException("导出数据出现异常");
//        } finally {
//            if (excelWriter != null) {
//                excelWriter.finish();
//            }
//            if (null != outputStream) {
//                IOUtils.closeQuietly(outputStream);
//            }
//        }
//    }
//
//
//    public static void repeatedWriteFile(File file, String sheetName, List<String> headers,
//                                         List<List<Object>> records,
//                                         IPage page,
//                                         PagedExport pagedExport) {
//        OutputStream outputStream = null;
//        ExcelWriter excelWriter = null;
//        try {
//            outputStream = new FileOutputStream(file);
//            //通用的样式(可以调整)
//            WriteCellStyle headWriteCellStyle = genCommonWriteCellStyle();
//            // 内容的策略
//            WriteCellStyle contentWriteCellStyle = genWriteCellStyle();
//            // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
//            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
//                    new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
//            excelWriter = EasyExcel.write(outputStream).build();
//            WriteSheet writeSheet = EasyExcel.writerSheet(sheetName)
//                    .head(genExcelHead(headers, sheetName)).registerWriteHandler(horizontalCellStyleStrategy)
//                    .build();
//            excelWriter.write(records, writeSheet);
//            while (true) {
//                page.setCurrent(page.getCurrent() + 1);
//                page.setRecords(null);
//                List ll = pagedExport.process(page);
//                if (CollectionUtils.isEmpty(ll)) {
//                    break;
//                }
//                excelWriter.write(ll, writeSheet);
//                if (ll.size() < page.getSize()) {
//                    break;
//                }
//            }
//        } catch (Exception e) {
//            log.error("exportXlsx error", e);
//            throw new RuntimeException("导出数据出现异常");
//        } finally {
//            if (excelWriter != null) {
//                excelWriter.finish();
//            }
//            if (null != outputStream) {
//                IOUtils.closeQuietly(outputStream);
//            }
//        }
//    }


    public static void repeatedWriteFileSplit(File file, String sheetName, List<String> headers,
                                              List<List<List<Object>>> recordsList) {
        OutputStream outputStream = null;
        ExcelWriter excelWriter = null;
        try {
            outputStream = new FileOutputStream(file);
            //通用的样式(可以调整)
            WriteCellStyle headWriteCellStyle = genCommonWriteCellStyle();
            // 内容的策略
            WriteCellStyle contentWriteCellStyle = genWriteCellStyle();
            // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
            excelWriter = EasyExcel.write(outputStream).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(sheetName)
                    .head(genExcelHead(headers, sheetName)).registerWriteHandler(horizontalCellStyleStrategy)
                    .build();
            for (List<List<Object>> records : recordsList) {
                excelWriter.write(records, writeSheet);
            }
        } catch (Exception e) {
            log.error("exportXlsx error", e);
            throw new RuntimeException("导出数据出现异常");
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
            if (null != outputStream) {
                IOUtils.closeQuietly(outputStream);
            }
        }
    }

}
